package middleware

import (
	"GIN-API/internal/utils"
	"github.com/casbin/casbin/v2"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v4"
	"net/http"
	"strings"
)

var enforcer *casbin.Enforcer

// SetEnforcer 设置 Casbin 实例
func SetEnforcer(e *casbin.Enforcer) {
	enforcer = e
}

// AuthMiddleware 认证中间件
func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 从请求头中获取认证令牌
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "未提供认证令牌"})
			c.Abort()
			return
		}
		// 提取认证令牌
		tokenString := strings.Replace(authHeader, "Bearer ", "", 1)
		token, err := utils.ValidateToken(tokenString)
		if err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "认证令牌解析失败"})
			c.Abort()
			return
		}

		if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
			username := claims["username"].(string)
			role := claims["role"].(string)
			userIDFlaot := claims["userID"].(float64)
			userID := uint(userIDFlaot)
			c.Set("username", username)
			c.Set("role", role)
			c.Set("userID", userID)
			// 进行 Casbin 权限验证
			obj := c.Request.URL.Path
			act := c.Request.Method
			ok, err := enforcer.Enforce(username, obj, act)
			if err != nil {
				c.JSON(http.StatusInternalServerError, gin.H{"error": "权限验证出错" + err.Error()})
				c.Abort()
				return
			}
			if !ok {
				c.JSON(http.StatusForbidden, gin.H{"error": "权限不足"})
				c.Abort()
				return
			}

			c.Next()
		} else {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "令牌验证未通过"})
			c.Abort()
			return
		}
	}
}
